import requests
from apps.system.models import SystemSetting
from common.exceptions import *
from hashlib import sha256
from tuntun.settings import GETUI
import time
import uuid
import json

class GetuiClient(object):
    def __init__(self):
        self.app_id = GETUI['AppID']
        self.app_key = GETUI['AppKey']

        self.authtoken = self.get_getui_authtoken()

        self.headers = {
            'Content-Type': 'application/json',
            'authtoken': self.authtoken,
        }

    def get_getui_authtoken(self):
        """此处需要根据业务实现"""
        ss = SystemSetting.objects.first()
        if not ss:
            raise ObjectNotFoundAPIException(code='SYSTEM_SETTING_NOT_FOUND', msg='系统配置不存在')
        authtoken = ss.get_getui_authtoken()
        return authtoken

    def push_single_transmission(self, cid, transmission_content, transmission_type=False, duration_begin=None, duration_end=None, push_info=None):
        url = 'https://restapi.getui.com/v1/%s/push_single' % self.app_id
        method = 'POST'
        # message
        message = {
            'appkey': self.app_key,
            'is_offline': False,
            'msgtype': 'transmission',
        }
        # transmission
        transmission = {
            'transmission_type': transmission_type,
            'transmission_content': json.dumps(transmission_content),
        }
        if duration_begin is not None and duration_end is not None:
            transmission['duration_begin'] = duration_begin
            transmission['duration_end'] = duration_end
        # 最终body
        data = {
            'message': message,
            'transmission': transmission,
            'cid': cid,
            'requestid': uuid.uuid4().hex[0:29]
        }
        # 判断push_info
        if push_info is not None:
            data['push_info'] = json.dumps(push_info)
        # 发送
        r = requests.post(url, json=data, headers=self.headers)

        print(r.headers)
        if r.status_code == 200:
            return r.status_code, r.json()
        else:
            return r.status_code, r.text


    def push_list_transmission_save_list_body(self, transmission_content, transmission_type=False, duration_begin=None, duration_end=None, push_info=None):
        url = 'https://restapi.getui.com/v1/%s/save_list_body' % self.app_id
        method = 'POST'
        # message
        message = {
            'appkey': self.app_key,
            'is_offline': False,
            'msgtype': 'transmission',
        }
        # transmission
        transmission = {
            'transmission_type': transmission_type,
            'transmission_content': json.dumps(transmission_content),
        }
        # 最终body
        data = {
            'message': message,
            'transmission': transmission,
            # 'requestid': uuid.uuid4().hex[0:23],
            # "requestid": "12111111111111111111111",
        }
        # 判断push_info
        if push_info is not None:
            data['push_info'] = push_info
        # 发送
        r = requests.post(url, json=data, headers=self.headers)
        print('PushListTransmissionSaveListBody: ', r.status_code, r.text, data)
        if r.status_code != 200:
            return r.status_code, r.text
        else:
            return r.status_code, r.json()

    def push_list_transmission(self, cids, taskid, need_detail=False):
        url = 'https://restapi.getui.com/v1/%s/push_list' % self.app_id
        method = 'POST'
        # data
        data = {
            'cid': cids,
            'taskid': taskid,
            'need_detail': need_detail,
            # "requestid": uuid.uuid4().hex[0:23],
            # "requestid": "12111111111111111111111",
        }
        r = requests.post(url, json=data, headers=self.headers)
        print('PushListTransmission: ', r.status_code, r.text, data)
        if r.status_code == 200:
            return r.status_code, r.json()
        else:
            return r.status_code, r.text

    def push_list_transmission_one_step(self, cids, transmission_content, transmission_type=True, duration_begin=None, duration_end=None, push_info=None, need_detail=False):
        status_code, rs = self.push_list_transmission_save_list_body(
            transmission_content=transmission_content,
            transmission_type=transmission_type,
            duration_begin=duration_begin,
            duration_end=duration_end,
            push_info=push_info
        )
        if type(rs) == dict and rs['result'] == 'ok':
            taskid = rs['taskid']
            return self.push_list_transmission(cids, taskid, need_detail=need_detail)
        else:
            return status_code, rs


    def push_single_notification(self, cid, notification_content):
        url = "https://restapi.getui.com/v1/%s/push_single" % self.app_id

        message = {
            'appkey': self.app_key,
            'is_offline': True,
            'msgtype': 'notification',
            "offline_expire_time": 10000000,
        }
        # notification
        style = {
            "type": 0,
            "is_ring": True,
            "is_vibrate": True,
            "is_clearable": True,
        }
        style.update(notification_content)
        notification = {
            "style": style,
            "transmission_type": True,
            "transmission_content": notification_content,
        }
        # data
        data = {
            "message": message,
            "notification": notification,
            "cid": cid,
        }

        # 发送
        r = requests.post(url, json=data, headers=self.headers)
        print('PushSingleNotification: ', r.status_code, r.text, data)
        if r.status_code == 200:
            return r.status_code, r.json()
        else:
            return r.status_code, r.text

    def push_list_notification_save_list_body(self, notification_content, title='', body=''):
        print('In push list notify save list body:', notification_content, title, body)
        url = "https://restapi.getui.com/v1/%s/save_list_body" % self.app_id

        message = {
            'appkey': self.app_key,
            'is_offline': True,
            "offline_expire_time": 10000000,
            'msgtype': 'notification',
        }
        # notification
        style = {
            "type": 0,
            "is_ring": True,
            "is_vibrate": True,
            "is_clearable": True,
        }
        style.update(notification_content)
        notification = {
            "style": style,
        }
        # data
        data = {
            "message": message,
            "notification": notification,
            "transmission": {
                "transmission_type": False,
                "transmission_content": "",
            },
            "push_info": {
                "aps": {
                    "alert": {
                        "title": title,
                        "body": body
                    },
                    "sound": "default",
                    "autoBadge":  "+1",
                },
                "content-available": -1,
            }
        }

        # 发送
        r = requests.post(url, json=data, headers=self.headers)
        print('In push list notify save list body: ', r.status_code, r.text, data)
        if r.status_code == 200:
            return r.status_code, r.json()
        else:
            return r.status_code, r.text

    def push_list_notification(self, cids, taskid, need_detail=False):
        print('In push list notify:', cids, taskid, need_detail)
        url = 'https://restapi.getui.com/v1/%s/push_list' % self.app_id
        # data
        data = {
            'cid': cids,
            'taskid': taskid,
            'need_detail': need_detail,
        }
        r = requests.post(url, json=data, headers=self.headers)
        print('In push list notify: ', r.status_code, r.text, data)
        if r.status_code == 200:
            return r.status_code, r.json()
        else:
            return r.status_code, r.text

    def push_list_notification_one_step(self, cids, notification_content, need_detail=False, title='', body=''):
        print('In push list notify one step:', cids, notification_content, title, body)
        status_code, rs = self.push_list_notification_save_list_body(notification_content, title, body)
        if type(rs) == dict and rs['result'] == 'ok':
            taskid = rs['taskid']
            return self.push_list_notification(cids, taskid, need_detail=need_detail)
        else:
            return status_code, rs